package com.jiangyao.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiangyao.common.exception.ServerException;
import com.jiangyao.common.utils.FtpClient;
import com.jiangyao.dao.IBannerDao;
import com.jiangyao.model.dto.backend.BannerDTO;
import com.jiangyao.model.dto.backend.BannerListPageDTO;
import com.jiangyao.model.entity.Banner;
import com.jiangyao.model.vo.backend.BannerDetailVO;
import com.jiangyao.service.BannerService;
import org.dozer.DozerBeanMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

/**
 * <p>
 * banner 服务实现类
 * </p>
 *
 * @author xiangyan
 * @since 2020-08-11
 */
@Service
public class BannerServiceImpl extends ServiceImpl<IBannerDao, Banner> implements BannerService {

	@Autowired
	private DozerBeanMapper dozerBeanMapper;

	@Autowired
	private IBannerDao bannerDao;

	@Override
	public Page<BannerDetailVO> getListPage(BannerListPageDTO listPageDTO) {
		Page<BannerDetailVO> page = new Page<>(listPageDTO.getPageNo(), listPageDTO.getPageSize());
		bannerDao.getListPage(page, listPageDTO);
		if (CollectionUtils.isEmpty(page.getRecords())) {
			return page;
		}
		page.getRecords().forEach(vo -> vo.setBannerImgFull(FtpClient.fullFtpUrl(vo.getBannerImg())));
		return page;
	}

	@Override
	public void add(BannerDTO bannerDTO) {
		Banner banner = dozerBeanMapper.map(bannerDTO, Banner.class);
		banner.setBannerId(null);
		banner.setStatus(1);
		this.save(banner);
	}

	@Override
	public BannerDetailVO getDetail(BannerDTO bannerDTO) {
		Banner banner = this.getById(bannerDTO.getBannerId());
		if (banner == null) {
			throw new ServerException(100, "banner不存在");
		}
		BannerDetailVO detailVO = dozerBeanMapper.map(banner, BannerDetailVO.class);
		detailVO.setBannerImgFull(FtpClient.fullFtpUrl(detailVO.getBannerImg()));
		return detailVO;
	}

	@Override
	public void edit(BannerDTO bannerDTO) {
		Banner banner = this.getById(bannerDTO.getBannerId());
		if (banner == null) {
			throw new ServerException(100, "banner不存在");
		}
		BeanUtils.copyProperties(bannerDTO, banner, "status");
		this.updateById(banner);
	}

	@Override
	public void editStatus(BannerDTO bannerDTO) {
		Banner banner = this.getById(bannerDTO.getBannerId());
		if (banner == null) {
			throw new ServerException(100, "banner不存在");
		}
		UpdateWrapper<Banner> updateWrapper = new UpdateWrapper<>();
		updateWrapper.eq("banner_id", bannerDTO.getBannerId());
		updateWrapper.set("status", bannerDTO.getStatus() == null ? 1 : bannerDTO.getStatus());
		this.update(updateWrapper);
	}
}
